// pages/alarm/alarm.js
const httprequest = require('../../utils/http_utils.js')
const common = require('../../utils/common.js')
const dateutil = require('../../utils/date_util.js')
var app = getApp();
var header = {
  'content-type': "application/x-www-form-urlencoded",
  "Cookie": "",
}
var session_id = wx.getStorageSync('SessionId'); //本地取存储的sessionID
if (session_id != "" && session_id != null) {
  header.Cookie = 'JSESSIONID' + session_id
}
Page({

	/**
	 * 页面的初始数据
	 */
  data: {
    heightInfo: '100%',
    openSimple: false,
    openResData: '',
    messageData: [], //告警消息列表
    totalNum: 0,
    counter: 1, //当前页
    pagesize: 10, // 一页显示多少条
    pageStart: 0, // 开始页数
    pageEnd: 0, // 结束页数
    isNoData: true,
    openSimpleData: {
      AppId: '40191',
      ProjId: '11',
      value: {
        message_type: 1000300,
        RecTS: 1553850216435,
        app_id: 40191,
        content: {
          extend: {},
          image: {
            data: '6709cefa-d5e3-4881-8e65-4ec70ca4450a',
            type: 3
          },
          handler: {},
          level: 5,
          sub_type: 'invade',
          advice: '',
          description: '',
          id: '804b1746-5e8e-473c-bcea-18de1e1e22bb',
          time: '1553850215127',
          position: {
            wId: 'bb11034e-4639-47aa-b801-34d3df24df23',
            level: 9,
            din: '144115194549120858',
            text: {
              floor: 'F7',
              tower: 'S'
            }
          },
          type: 'security_monitoring',
          status: 'unprocessed'
        }
      },
      ReceiveTimestamp: '1553850215127'
    }, //弹屏数据
    positionText: '',
    imageData: '', //弹屏图片地址
    title: '报警',
    windowHeight: 0,
    uploading: false,
    downloading: false,
    noMore: false,
    loadingFailed: false,
    isshoworder: true, //默认跳转到上一页
    isHidden: true, //是否隐藏dialog
    titleMsg: "", //消息标题
    cancleBtn: false,
    drawerTitle: "",
    titleTime: "",
    showzanwu: false,
    AlarmTypeList: ["invade", "fire", "retention", "crowd"], //报警类型集合
  },
  wancheng() {
    var _this = this;
    var res = _this.data.openSimpleData;
    var imageData = _this.data.imageData;
    var positionText = _this.data.positionText;
    var paramInfo = {
      level: dateutil.formatTypeLevel(res.value.content.level),
      type: dateutil.formatTypeData(res.value.content.level),
      time: dateutil.dateFormat(new Date()),
      sub_type: dateutil.formatType(res.value.content.sub_type),
      description: res.value.content.description,
      location: "",
      id: res.value.content.id,
      processor: null,
      din: res.value.content.position.din,
      image: res.value.content.image,
      imageData: ""
    }
    _this.setData({
      isHidden: true,
    })
    console.log(JSON.stringify(paramInfo))
    wx.navigateTo({
      url: '/pages/alarmDetail/alarmDetail?msg=' + JSON.stringify(paramInfo)
    })

  },
  //跳转到详情
  jumpdet(v) {
    console.log(JSON.stringify(v.currentTarget.dataset.rowguid))
    var res = v.currentTarget.dataset.rowguid;
    if (res != null) {
      wx.navigateTo({
        url: '/pages/alarmDetail/alarmDetail?msg=' + JSON.stringify(res)
      })
    }
  },
  //获取信息
  getSystemInfo: function () {
    var _this = this
    wx.getSystemInfo({
      success: function (res) {
        _this.setData({
          windowWidth: res.windowWidth,
          windowHeight: res.windowHeight
        })
      },
      fail: function (res) { },
      complete: function (res) { },
    })
  },
  //上拉
  scrollToLower: function () {
    var _this = this;
    _this.setData({
      heightInfo: 'auto'
    })
    console.log(_this.data.totalNum + "**" + _this.data.pagesize)
    var pages = Math.round((_this.data.totalNum / _this.data.pagesize) * 100) / 100
    if (_this.data.counter > pages) {
      _this.setData({
        noMore: true,
        downloading: false
      })
    } else {
      _this.setData({
        noMore: false,
        downloading: true
      })
      _this.setData({
        counter: _this.data.counter + 1
      })
      try {
        wx.showLoading({
          title: "正在加载中...",
        })
        wx.request({
          url: app.globalData.apiInfo.GetAlarmInfoApi,
          data: {
            ProjectGuid: app.globalData.ProjectGuid,
            type: 'security_monitoring',
            status: 'unprocessed',
            subType: wx.getStorageSync('UserInfo').AppLogin.AlarmType,
            page: _this.data.counter,
            size: 10,
            level: '',
            heightInfo: 'auto',
            imgFlag: true
          },
          method: "POST",
          header: header,
          success: function (data) {
            wx.hideLoading();
            var res = JSON.parse(data.data);
            var arrRes = new Array();
            arrRes = _this.data.messageData;
            if (res != null) {
              if (res.data.length > 0) {
                for (var i = 0; i < res.data.length; i++) {
                  var _position = JSON.parse(res.data[i].position);
                  var param = {
                    "type": dateutil.formatTypeData(res.data[i].type),
                    "status": res.data[i].status,
                    "subType": dateutil.formatType(res.data[i].subType),
                    "level": dateutil.formatTypeLevel(res.data[i].level),
                    "BeginTime": res.data[i].BeginTime,
                    "EndTime": res.data[i].EndTime,
                    "Url": res.data[i].Url,
                    "dinCode": res.data[i].dinCode,
                    "id": res.data[i].id,
                    "processor": res.data[i].processor,
                    "token": res.data[i].token,
                    "handler": res.data[i].handler,
                    "positionText": res.data[i].positionText,
                    "time": dateutil.formatDatetwo(res.data[i].time),
                    "description": res.data[i].description,
                    "positionText": res.data[i].positionText,
                    "file_id": res.data[i].file_id,
                    "message_type": res.data[i].message_type,
                    "image": res.data[i].image,
                    "imageData": res.data[i].imageData,
                  }
                  arrRes.push(param);
                }
                //赋值
                _this.setData({
                  messageData: arrRes
                })

                //总数
                _this.setData({
                  totalNum: res.count
                })
              } else {
                _this.setData({
                  noMore: true,
                  downloading: false
                })
              }
            }
          },
          fail: function (error) {
            wx.hideLoading();
          }
        })
      } catch (e) {
        console.log(e.message);
      }
    }
  },

  //初始化数据
  initData: function () {
    var _this = this;
    // console.log(wx.getStorageSync('UserInfo').AppLogin.AlarmType)
    var parameter = {
      PageSize: 10,
      CurrentPage: 1
    };
    try {
      wx.showLoading({
        title: "正在加载中...",
      })
      // console.log("请求头：", header)
      wx.request({
        url: app.globalData.apiInfo.GetAlarmInfoApi,
        data: {
          ProjectGuid: app.globalData.ProjectGuid,
          type: 'security_monitoring',
          status: 'unprocessed',
          subType: wx.getStorageSync('UserInfo').AppLogin.AlarmType,
          page: parameter.CurrentPage,
          size: parameter.PageSize,
          level: '',
          heightInfo: 'auto',
          imgFlag: true
        },
        method: "POST",
        header: header,
        success: function (data) {
          wx.hideLoading();
          var res = JSON.parse(data.data);
          console.log('alarm初始化数据', JSON.stringify(res), res.count)
          var arrRes = new Array();
          if (res != null && res.count != 0) {
            _this.setData({
              uploading: false,
              showzanwu: false
            })
            for (var i = 0; i < res.data.length; i++) {
              var _position = JSON.parse(res.data[i].position);
              //console.log(_position)
              //console.log(res.data[i].dinCode)
              var param = {
                "type": dateutil.formatTypeData(res.data[i].type),
                "status": res.data[i].status,
                "subType": dateutil.formatType(res.data[i].subType),
                "level": dateutil.formatTypeLevel(res.data[i].level),
                "BeginTime": res.data[i].BeginTime,
                "EndTime": res.data[i].EndTime,
                "Url": res.data[i].Url,
                "dinCode": _position.din,
                "id": res.data[i].id,
                "processor": res.data[i].processor,
                "token": res.data[i].token,
                "handler": res.data[i].handler,
                "position": _position,
                "time": dateutil.formatDatetwo(res.data[i].time),
                "description": res.data[i].description,
                "positionText": res.data[i].positionText,
                "file_id": res.data[i].file_id,
                "message_type": res.data[i].message_type,
                "image": res.data[i].image,
                "imageData": res.data[i].imageData,
              }
              arrRes.push(param);
            }
            //调用排序
            //arrRes.sort(common.compare('status')).reverse();

            //赋值
            _this.setData({
              messageData: arrRes
            })

            //总数
            _this.setData({
              totalNum: res.count
            })

            if (arrRes.length > 10) {
              _this.setData({
                heightInfo: 'auto'
              })
            } else {
              _this.setData({
                heightInfo: 'auto'
              })
            }

          } else {
            _this.setData({
              showzanwu: true
            })
            console.log('暂无数据');
          }
        },
        fail: function (error) {
          wx.hideLoading();
          _this.setData({
            showzanwu: true
          })
        }
      })
    } catch (e) {
      console.log(e.message);
    }
  },
  //初始化webscoket
  initScoket: function () {
    var websocket = null;
    var token = "";
    var openRes = "";
    var _this = this;
    console.log(wx.getStorageSync('token')+"---------------------------------TOKEN")
    // console.log(JSON.stringify(app))
    try {
      wx.request({
        url: app.globalData.apiInfo.loginApi,
        data: {
          ProjectGuid: app.globalData.ProjectGuid
        },
        method: "POST",
        header: header,
        success: function (data) {
          console.log('alarm初始化webscoket', data)
          if (data != null) {
            token = data.data;
            wx.setStorageSync("token", token)
            console.log(app.globalData.WebScoketUrl + "space-websocket/datahub/swmp/messageHub?token=" + token)
            //建立连接
            wx.connectSocket({
              url: app.globalData.WebScoketUrl + "?token=" + token,
              success: function (e) {
                console.log(JSON.stringify(e))
              },
              fail: function (e) {
                console.log(JSON.stringify(e))
              }
            })
            //连接成功
            wx.onSocketOpen(function () {
              console.log("连接成功")
              console.log("AlarmType:" + _this.data.AlarmTypeList.length)

              for (var i = 0; i < _this.data.AlarmTypeList.length; i++){
                if (_this.data.AlarmTypeList[i] == "invade"){
                  console.log('报警类型：invade')
                  wx.sendSocketMessage({
                    data: "SUBSCRIBE 0.1\r\nFRAME-ID:1571814268616626\r\nTOPIC:/space/datahub/security_monitoring/invade\r\n\0"
                  })
                  wx.sendSocketMessage({
                    data: "REQUEST 0.1\r\nFRAME-ID:fdsafsaf\r\nCONTENT-TYPE:text/plain;charset=utf-8\r\nCONTENT-LENGTH:4\r\nDESTINATION:/space/datahub/security_monitoring/invade\r\n\r\n\0keep\r\n\0"
                  })
                }
                if (_this.data.AlarmTypeList[i] == "fire"){
                  console.log('报警类型：fire')
                  wx.sendSocketMessage({
                    data: "SUBSCRIBE 0.1\r\nFRAME-ID:1571814268616626\r\nTOPIC:/space/datahub/security_monitoring/fire\r\n\0"
                  })
                  wx.sendSocketMessage({
                    data: "REQUEST 0.1\r\nFRAME-ID:fdsafsaf\r\nCONTENT-TYPE:text/plain;charset=utf-8\r\nCONTENT-LENGTH:4\r\nDESTINATION:/space/datahub/security_monitoring/fire\r\n\r\n\0keep\r\n\0"
                  })
                }
                if (_this.data.AlarmTypeList[i] == "retention") {
                  console.log('报警类型：retention')
                  wx.sendSocketMessage({
                    data: "SUBSCRIBE 0.1\r\nFRAME-ID:1571814268616626\r\nTOPIC:/space/datahub/security_monitoring/retention\r\n\0"
                  })
                  wx.sendSocketMessage({
                    data: "REQUEST 0.1\r\nFRAME-ID:fdsafsaf\r\nCONTENT-TYPE:text/plain;charset=utf-8\r\nCONTENT-LENGTH:4\r\nDESTINATION:/space/datahub/security_monitoring/retention\r\n\r\n\0keep\r\n\0"
                  })
                }
                if (_this.data.AlarmTypeList[i] == "crowd") {
                  console.log('报警类型：crowd')
                  wx.sendSocketMessage({
                    data: "SUBSCRIBE 0.1\r\nFRAME-ID:1571814268616626\r\nTOPIC:/space/datahub/security_monitoring/crowd\r\n\0"
                  })
                  wx.sendSocketMessage({
                    data: "REQUEST 0.1\r\nFRAME-ID:fdsafsaf\r\nCONTENT-TYPE:text/plain;charset=utf-8\r\nCONTENT-LENGTH:4\r\nDESTINATION:/space/datahub/security_monitoring/crowd\r\n\r\n\0keep\r\n\0"
                  })
                }
              }

              // if (wx.getStorageSync('UserInfo').AppLogin.AlarmType == "invade") {
              //   wx.sendSocketMessage({
              //     data: "SUBSCRIBE 0.1\r\nFRAME-ID:1571814268616626\r\nTOPIC:/space/datahub/security_monitoring/invade\r\n\0"
              //   })
              //   wx.sendSocketMessage({
              //     data: "REQUEST 0.1\r\nFRAME-ID:fdsafsaf\r\nCONTENT-TYPE:text/plain;charset=utf-8\r\nCONTENT-LENGTH:4\r\nDESTINATION:/space/datahub/security_monitoring/invade\r\n\r\n\0keep\r\n\0"
              //   })
              // }
              // if (wx.getStorageSync('UserInfo').AppLogin.AlarmType == "fire") {
              //   wx.sendSocketMessage({
              //     data: "SUBSCRIBE 0.1\r\nFRAME-ID:1571814268616626\r\nTOPIC:/space/datahub/security_monitoring/fire\r\n\0"
              //   })
              //   wx.sendSocketMessage({
              //     data: "REQUEST 0.1\r\nFRAME-ID:fdsafsaf\r\nCONTENT-TYPE:text/plain;charset=utf-8\r\nCONTENT-LENGTH:4\r\nDESTINATION:/space/datahub/security_monitoring/fire\r\n\r\n\0keep\r\n\0"
              //   })
              // }
              // if (wx.getStorageSync('UserInfo').AppLogin.AlarmType == "fire,invade" || wx.getStorageSync('UserInfo').AppLogin.AlarmType ==
              //   "invade,fire") {
              //   wx.sendSocketMessage({
              //     data: "SUBSCRIBE 0.1\r\nFRAME-ID:1571814268616626\r\nTOPIC:/space/datahub/security_monitoring/invade\r\n\0"
              //   })
              //   wx.sendSocketMessage({
              //     data: "REQUEST 0.1\r\nFRAME-ID:fdsafsaf\r\nCONTENT-TYPE:text/plain;charset=utf-8\r\nCONTENT-LENGTH:4\r\nDESTINATION:/space/datahub/security_monitoring/invade\r\n\r\n\0keep\r\n\0"
              //   })
              //   wx.sendSocketMessage({
              //     data: "SUBSCRIBE 0.1\r\nFRAME-ID:1571814268616626\r\nTOPIC:/space/datahub/security_monitoring/fire\r\n\0"
              //   })
              //   wx.sendSocketMessage({
              //     data: "REQUEST 0.1\r\nFRAME-ID:fdsafsaf\r\nCONTENT-TYPE:text/plain;charset=utf-8\r\nCONTENT-LENGTH:4\r\nDESTINATION:/space/datahub/security_monitoring/fire\r\n\r\n\0keep\r\n\0"
              //   })
              // }
            })

            wx.onSocketClose(function (res) {
              _this.initScoket();
              console.log('WebSocket 已关闭！')
            })

            //接收数据
            wx.onSocketMessage(function (event) {
              // console.log(JSON.stringify("**************:" + JSON.stringify(event)));
              var s = event.data;
              console.log('接收数据', JSON.stringify("**************:" + s));
              var a = s.split("\r\n\r\n\u0000");
              if (a[1] == "") {
                console.log(event.data)
              } else {
                a[1] = a[1].replace(/[\r\n]/g, "");
                // console.log(a[1].substring(0, a[1].length - 1));
                if (a[1].indexOf("SUBSCRIBE") != -1 || a[1].indexOf("OK") != -1) {
                  //openRes = "1";
                } else {
                  openRes = a[1];
                  var _alarmData = "";
                  var _alarmType = "";
                  if (openRes != '1' && openRes.length > 0) {
                    openRes = openRes.substring(0, openRes.length - 1);
                    console.log('接收数据', typeof (openRes), openRes)
                    var sRes = JSON.parse(openRes);
                    _alarmData = sRes.value.content.sub_type;
                    _this.setData({
                      openSimpleData: sRes,
                      drawerTitle: dateutil.formatType(sRes.value.content.sub_type),
                      titleTime: dateutil.dateFormat(new Date()),
                      titleMsg: "兰生大厦"
                    })
                    if (_alarmData == "fire") {
                      _alarmType = "火警报警";
                      var parameter = {
                        "Content": _alarmType,
                        "UserPhones": wx.getStorageSync('UserInfo').AppLogin.Mobile,
                        "AlarmId": "",
                        "Address": "",
                      }
                      var _addressCode = JSON.stringify(sRes.value.content).indexOf('position') != -1 ? sRes.value.content.position.din : ''
                      console.log('火警报警啊', JSON.stringify(sRes.value.content), _addressCode)
                      //获取位置信息
                      try {
                        wx.request({
                          url: app.globalData.apiInfo.DeviceListApi,
                          data: {
                            ProjectGuid: app.globalData.ProjectGuid,
                            dinCode: _addressCode
                          },
                          method: "POST",
                          header: header,
                          success: function (data) {
                            if (data != null) {
                              var res = data.data;
                              parameter.Address = res;
                            } else {
                              parameter.Address = "-"
                            }
                          },
                          fail: function (error) {
                            wx.hideLoading();
                          }
                        })
                      } catch (e) {
                        wx.hideLoading();
                        console.log(e.message);
                      }
                      //value.content.position.din
                    } else {
                      _alarmType = "入侵报警";
                      var parameter = {
                        "Content": _alarmType,
                        "UserPhones": wx.getStorageSync('UserInfo').AppLogin.Mobile,
                        "AlarmId": "",
                        "Address": "",
                      }
                      var _addressCode = JSON.stringify(sRes.value.content).indexOf('position') != -1 ? sRes.value.content.position.din : ''
                      console.log('入侵报警啊', JSON.stringify(sRes.value.content), _addressCode)
                      try {
                        wx.request({
                          url: app.globalData.apiInfo.DeviceListApi,
                          data: {
                            ProjectGuid: app.globalData.ProjectGuid,
                            dinCode: _addressCode
                          },
                          method: "POST",
                          header: header,
                          success: function (data) {
                            if (data != null) {
                              var res = data.data;
                              parameter.Address = res;
                            } else {
                              parameter.Address = "-"
                            }
                            wx.hideLoading();
                          },
                          fail: function (error) {
                            wx.hideLoading();
                          }
                        })
                      } catch (e) {
                        wx.hideLoading();
                        console.log(e.message);
                      }
                    }
                    try {
                      if (_this.data.openSimpleData.value.content.image != null && _this.data.openSimpleData.value.content
                        .image != undefined) {
                        wx.request({
                          url: app.globalData.apiInfo.downLoadApi,
                          data: {
                            ProjectGuid: app.globalData.ProjectGuid,
                            file_id: _this.data.openSimpleData.value.content.image.data
                          },
                          method: "POST",
                          header: header,
                          success: function (data) {
                            if (data != null) {
                              _this.setData({
                                isHidden: false
                              })
                              var res = JSON.parse(data.data);
                              var resInfo = res.data;
                              // console.log(res.data)
                              if (resInfo != null) {
                                _this.setData({
                                  imageData: resInfo.downloadUrl
                                })
                              }
                            } else {
                              _this.setData({
                                isHidden: true
                              })
                            }
                          },
                          fail: function (error) {
                            console.log('websocket连接失败！' + JSON.stringify(error));
                            _this.setData({
                              isHidden: true
                            })
                            _this.setData({
                              positionText: "",
                              imageData: "../images/img.png"
                            })
                          }
                        })
                      } else {
                        _this.setData({
                          positionText: "",
                          imageData: "../images/img.png"
                        })
                      }
                      openRes = '';
                    } catch (error) {
                      openRes = '';
                      _this.setData({
                        positionText: "",
                        imageData: "../images/img.png"
                      })
                    }
                  }
                }
              }
            })
            //连接失败
            wx.onSocketError(function (res) {
              console.log('websocket连接失败！' + JSON.stringify(res));
            })
          } else {
            console.log("登录失败");
          }
        },
        fail: function (error) {
          console.log('websocket连接失败！' + JSON.stringify(error));
        }
      })
    } catch (e) {
      console.log('websocket连接失败！' + JSON.stringify(e));
    }
  },
	/**
	 * 生命周期函数--监听页面加载
	 */
  onLoad: function (options) {
    var _this = this;

    // var AlarmType = wx.getStorageSync('UserInfo').AppLogin.AlarmType
    // _this.setData({
    //     AlarmTypeList: AlarmType.split(",")
    // })
    // console.log(JSON.stringify(_this.data.AlarmTypeList.length) + '---------------------------缓存报警类型集合')

    _this.getSystemInfo();
    _this.refreshView = this.selectComponent("#refreshView")
    _this.initScoket();
    // setInterval(() => {
    //   _this.setData({
    //     isHidden: false
    //   });
    // }, 10000);
  },

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
  onReady: function () {

  },

	/**
	 * 生命周期函数--监听页面显示
	 */
  onShow: function () {
    this.initData();
  },

	/**
	 * 生命周期函数--监听页面隐藏
	 */
  onHide: function () {

  },

	/**
	 * 生命周期函数--监听页面卸载
	 */
  onUnload: function () {

  },

  //触摸开始
  handletouchstart: function (event) {
    this.refreshView.handletouchstart(event)
  },
  //触摸移动
  handletouchmove: function (event) {
    this.refreshView.handletouchmove(event)
  },
  //触摸结束
  handletouchend: function (event) {
    this.refreshView.handletouchend(event)
  },
  //触摸取消
  handletouchcancel: function (event) {
    this.refreshView.handletouchcancel(event)
  },
  //页面滚动
  onPageScroll: function (event) {
    this.refreshView.onPageScroll(event)
  },

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
  onPullDownRefresh: function () {
    setTimeout(() => {
      console.log("scrollToUpper")
      var _this = this
      _this.setData({
        uploading: true,
        noMore: false,
        counter: 1,
        messageData: [],
        heightInfo: 'auto',
        downloading: false,
        loadingFailed: false,
      })
      _this.initData()
      this.refreshView.stopPullRefresh()
    }, 1000)

  },

	/**
	 * 页面上拉触底事件的处理函数
	 */
  onReachBottom: function () {
    //this.scrollToLower();
  },

	/**
	 * 用户点击右上角分享
	 */
  onShareAppMessage: function () {

  }
})
